package com.water.camera.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.water.camera.App;
import com.water.camera.BuildConfig;
import com.water.camera.bean.MediaData;
import com.water.camera.bean.PageIndex;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Read {

    public static void toRead(Activity activity, Runnable runnable) {
        toSetting(activity, runnable);
    }

    public static boolean hasPermission(String permission) {
        return ContextCompat.checkSelfPermission(App.getApp(), permission) == PackageManager.PERMISSION_GRANTED;
    }

    private static void toSetting(Activity activity, Runnable runnable) {
        XXPermissions.with(activity).permission(Permission.MANAGE_EXTERNAL_STORAGE).request(new OnPermissionCallback() {
            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                if (!allGranted) {
                    return;
                }
                runnable.run();
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                if (doNotAskAgain) {
                    new MaterialAlertDialogBuilder(activity).setMessage("需要您在设置中授予读写存储权限").setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
                                intent.setData(uri);
                                activity.startActivityForResult(intent, 120);
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).create().show();
                }
            }
        });
    }

    boolean isLoadContinue;

    public List<MediaData> loadImageData(Context context, int page) {
        String dirPathName = "";
        int pageSizeData = 50;

        List<MediaData> mediaDataList = new ArrayList<>();
        final String[] imageProjection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.DATE_ADDED, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT, MediaStore.MediaColumns.BUCKET_DISPLAY_NAME};
        String mImageSelection = MediaStore.Images.Media.DATA + " like?";
        String[] mImageSelectionArgs = new String[]{"%" + dirPathName + "%"};
        Cursor cursor = null;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                Bundle bundle = new Bundle();
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, TextUtils.isEmpty(dirPathName) ? null : mImageSelection);
                bundle.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, TextUtils.isEmpty(dirPathName) ? null : mImageSelectionArgs);
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, imageProjection[5] + " DESC");
                bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, pageSizeData);
                bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, page * pageSizeData);
                cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection, bundle, null);
            } else {
                cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection, TextUtils.isEmpty(dirPathName) ? null : mImageSelection, TextUtils.isEmpty(dirPathName) ? null : mImageSelectionArgs, imageProjection[5] + " DESC LIMIT " + page * pageSizeData + " , " + pageSizeData);
            }

        } catch (SecurityException e) {
            e.printStackTrace();
        }
        boolean hasItem = false;
        while (cursor != null && cursor.moveToNext()) {
            try {
                hasItem = true;
                int imgId = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[0]));
                String imageName = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[1]));
                String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[2]));
                long imgSize = cursor.getLong(cursor.getColumnIndexOrThrow(imageProjection[3]));
                String imageMimeType = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[4]));
                long imageAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(imageProjection[5]));
                int imageWidth = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[6]));
                int imageHeight = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[7]));

                Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imgId));

                if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
                    if (TextUtils.isEmpty(imagePath)) {
                        continue;
                    }

                    File imageFile = new File(imagePath);
                    if (!imageFile.exists() || imageFile.length() <= 0) {
                        continue;
                    }
                }
                if (!HVEUtil.isLegalImage(imagePath)) {
                    isLoadContinue = true;
                    continue;
                }

                if (imageWidth == 0 || imageHeight == 0) {
                    BitmapFactory.Options options = BitmapDecodeUtils.getBitmapOptions(imagePath);
                    imageWidth = options.outWidth;
                    imageHeight = options.outHeight;
                }
                if (imageWidth == 0 || imageHeight == 0) {
                    isLoadContinue = true;
                    continue;
                }
                MediaData mediaData = MediaPickManager.getInstance().updateSelectMediaData(imagePath);
                if (mediaData != null) {
                    mediaData.setDirName(dirPathName);
                    mediaDataList.add(mediaData);
                } else {
                    MediaData item = new MediaData();
                    item.setDirName(dirPathName);
                    item.setName(imageName);
                    item.setPath(imagePath);
                    item.setUri(uri);
                    item.setSize(imgSize);
                    item.setMimeType(imageMimeType);
                    item.setAddTime(imageAddTime);
                    item.setWidth(imageWidth);
                    item.setHeight(imageHeight);
                    mediaDataList.add(item);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (mediaDataList.isEmpty() && hasItem) {
            return loadImageData(context, page + 1);
        }
        EventBus.getDefault().post(new PageIndex(page));
        return mediaDataList;
    }

    private static final int MAX_VIDEO_WIDTH = 4096;

    public List<MediaData> loadVideo(Context context, int page) {
        String aDirName = "";
        int aPageSize = 50;
        List<MediaData> videos = new ArrayList<>();
        final String[] videoProjections = {MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.MIME_TYPE, MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media.DURATION, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT};

        String mVideoSelection = MediaStore.Video.Media.DATA + " like?";
        String[] mVideoSelectionArgs = new String[]{"%" + aDirName + "%"};
        Cursor cursor;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                Bundle bundle = new Bundle();
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, TextUtils.isEmpty(aDirName) ? null : mVideoSelection);
                bundle.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs);
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, videoProjections[5] + " DESC");
                bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, aPageSize);
                bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, page * aPageSize);
                cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjections, bundle, null);
            } else {
                cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjections, TextUtils.isEmpty(aDirName) ? null : mVideoSelection, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs, videoProjections[5] + " DESC LIMIT " + page * aPageSize + " , " + aPageSize);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return videos;
        }

        boolean hasItem = false;
        while (cursor != null && cursor.moveToNext()) {
            try {
                hasItem = true;
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[0]));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[1]));
                String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[2]));
                long videoSize = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[3]));
                String videoMimeType = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[4]));
                long videoAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[5]));
                long videoDuration = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[6]));
                int videoWidth = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[7]));
                int videoHeight = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[8]));

                Uri uri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));

                if (!Utils.isVideoByPath(videoPath)) {
                    isLoadContinue = true;
                    continue;
                }

                if (videoDuration < 500) {
                    isLoadContinue = true;
                    continue;
                }

                if (videoWidth > MAX_VIDEO_WIDTH || videoHeight > MAX_VIDEO_WIDTH) {
                    isLoadContinue = true;
                    continue;
                }

                if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
                    if (TextUtils.isEmpty(videoPath)) {
                        isLoadContinue = true;
                        continue;
                    }

                    File file = new File(videoPath);
                    if (!file.exists() || file.length() <= 0) {
                        isLoadContinue = true;
                        continue;
                    }
                }
                MediaData mediaData = MediaPickManager.getInstance().updateSelectMediaData(videoPath);
                if (mediaData != null) {
                    mediaData.setDirName(aDirName);
                    videos.add(mediaData);
                } else {
                    MediaData item = new MediaData();
                    item.setDirName(aDirName);
                    item.setName(videoName);
                    item.setPath(videoPath);
                    item.setUri(uri);
                    item.setSize(videoSize);
                    item.setMimeType(videoMimeType);
                    item.setAddTime(videoAddTime);
                    item.setDuration(videoDuration);
                    item.setWidth(videoWidth);
                    item.setHeight(videoHeight);
                    videos.add(item);
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (videos.isEmpty() && hasItem) {
            return loadVideo(context, page + 1);
        }
        EventBus.getDefault().post(new PageIndex(page));
        return videos;
    }
}
